#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import hashlib
import time
from common import L
from common.tools import singleton, getEnv
__author__ = 'Administrator'


@singleton
class MyRequest():

	def __init__(self):
		from urllib3 import disable_warnings
		disable_warnings()
		self.headers = {
			'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
		}
		self.host = getEnv('host')

	def reset(self):
		from urllib3 import disable_warnings
		disable_warnings()
		self.headers = {
			'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
		}
		self.host = getEnv('host')
		return self

	def addHeaders(self, headers: dict):
		for k ,v in headers.items():
			self.headers[k] = v

	def getContentType(self, resp):
		return resp.headers.get('Content-Type', None)

	def getCookies(self, resp):
		return resp.cookies

	def sleep(self, s):
		time.sleep(s)

	def getTime(self, resp):
		"""获取响应执行的时间,单位s"""
		return resp.elapsed.total_seconds()

	def getCode(self, resp):
		return resp.status_code

	def urlJoin(self, api, host = None):
		host = host if host else self.host
		from urllib.parse import urljoin
		return urljoin(host, api)

	def send(self, method='GET', url=None, **kw):
		try:
			self.url = self.urlJoin(url)
			L.info(self.url)
			if 'headers' in kw:
				self.addHeaders(kw['headers'])
				kw.pop('headers')
			return requests.request(method, self.url, headers = self.headers, **kw)
		except BaseException as e:
			L.error(e)

	def __getattr__(self, item):
		if hasattr(requests, item):
			L.warning('"{}" not in MyRequest,suggest override'.format(item))
			_item = getattr(requests, item)
			from types import FunctionType, MethodType
			if isinstance(_item, (FunctionType, MethodType)) or callable(_item):
				def wrapper(*args, **kw):
					return _item(*args, **kw)
				return wrapper
			else:
				return _item
		else:
			raise AttributeError('Unkown attribute: %s' % item)

	def parseBody(self, body):
		secret_key = getEnv('secret_key')
		s_key = sorted(body.keys(), reverse=False)
		beforSign = ''
		for k in s_key:
			if body[k]:
				beforSign += '{}={}&'.format(k, body[k])
		beforSign += secret_key
		sign = hashlib.md5(beforSign.encode('utf-8')).hexdigest()
		body['sign'] = sign
		return body

if __name__ == '__main__':
	m = MyRequest()
	m.send('GET', "/api/login")
	r = m.send('GET', "https://www.baidu.com/search?key=s")
	# L.info(r.text)



